package com.javaee.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.javaee.ejb.entity.Activity;
import com.javaee.ejb.entity.Employee;
import com.javaee.ejb.session.ActivityManagerRemote;
import com.javaee.ejb.session.EmployeeManagerRemote;
import com.javaee.ejb.session.ProjectManagerRemote;

/**
 * Servlet implementation class Project
 */
public class Project extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private List<String> error = new ArrayList<String>(); 
	
	@EJB
	ProjectManagerRemote proj;
	@EJB
	EmployeeManagerRemote emp;
	@EJB
	ActivityManagerRemote act;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Project() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(arg0, arg1);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("idProject");
		String create = request.getParameter("create");
		String activites = request.getParameter("activites");
		String delete = request.getParameter("delete");
		StringBuilder sb = new StringBuilder("");
		
		if(activites != null)
		{
			List<Activity> lact = act.getProjectActivities(Integer.parseInt(activites)); 
			StringBuilder act = new StringBuilder("");
			Iterator<Activity> it = lact.iterator();
			while(it.hasNext())
			{
				System.out.println("a");
				Activity a = it.next();
				Employee e = emp.GetEmployeParId(a.getEmployeeIdemployee());
				act.append("<tr><td>"+a.getDescription()+"</td><td>"+a.getCharge()+"</td><td>"+a.getDayAct()+"</td><td>"+e.getUsername()+"</td></tr>");
			}
			request.setAttribute("activites",act.toString());
			request.getRequestDispatcher("activitesParProjets.jsp").forward(request, response);
		}
		else
		if(delete != null)
		{
			proj.DeleteProject(Integer.parseInt(delete));
			HttpSession session = request.getSession();
			request.setAttribute("projects", getProjects(((Employee)session.getAttribute("currentEmp")).getIdemployee()));
			request.setAttribute("projectsManager", getProjectsManager(((Employee)session.getAttribute("currentEmp")).getIdemployee()));
			request.setAttribute("errors",sb.toString());
			request.getRequestDispatcher("projects.jsp").forward(request, response);
		}
		else
		if(create != null && create.equals("1")) // Creation
		{
			request.setAttribute("errors",sb.toString());
			request.setAttribute("employees",getEmployees());
			request.getRequestDispatcher("createproject.jsp").forward(request, response);
		}
		else
		if(id != null && !id.equals("")) // Modification
		{
			try
			{
				com.javaee.ejb.entity.Project p = proj.GetProjetParId(Integer.parseInt(id));
				request.setAttribute("name", p.getName());
				request.setAttribute("budject", p.getBudject());
				request.setAttribute("description", p.getDescription());
				request.setAttribute("employees",getEmployees(p.getManagerIdemployee()));
				request.setAttribute("id",p.getIdproject());
			}
			catch(Exception nre)
			{				
				error.add("ce projet n'existe pas");
				while(!error.isEmpty())
				{
					int index = error.size()-1;
					sb.append("<li style='color:red;'>Erreur : "+error.get(index)+"</li>");
					error.remove(index);
				}
			}
			
			request.setAttribute("errors",sb.toString());
			request.getRequestDispatcher("updateProject.jsp").forward(request, response);
			
		}
		else // Création
		{
			while(!error.isEmpty())
			{
				int index = error.size()-1;
				sb.append("<li style='color:red;'>Erreur : "+error.get(index)+"</li>");
				error.remove(index);
			}
			
			request.setAttribute("employees",getEmployees());
			request.setAttribute("errors",sb.toString());
			
			if(!sb.toString().equals(""))
				request.getRequestDispatcher("createproject.jsp").forward(request, response);
			else
			{
				HttpSession session = request.getSession();
				request.setAttribute("projects", getProjects(((Employee)session.getAttribute("currentEmp")).getIdemployee()));
				request.setAttribute("projectsManager", getProjectsManager(((Employee)session.getAttribute("currentEmp")).getIdemployee()));
				request.getRequestDispatcher("projects.jsp").forward(request, response);
			}
		}
		
		
	}

	public String getEmployees(int defaut)
	{
		List<Employee> employees = emp.GetEmployes();
		
		Iterator<Employee> iter = employees.iterator();
		StringBuilder lstEmpl = new StringBuilder();
		String opt = "";
		while (iter.hasNext()) {
		    Employee element = iter.next();
		    if(defaut == element.getIdemployee())
		    	opt = "selected=\"selected\"";
		    else
		    	opt = "";
		    lstEmpl.append("<option "+opt+" value='"+element.getIdemployee()+"'>"+
		    element.getFirstname()+" "+element.getLastname()+"</option>\n");
		}	
		
		return lstEmpl.toString();
	}
	
	public String getEmployees()
	{
		List<Employee> employees = emp.GetEmployes();
		
		Iterator<Employee> iter = employees.iterator();
		StringBuilder lstEmpl = new StringBuilder();
		while (iter.hasNext()) {
		    Employee element = iter.next();
		    lstEmpl.append("<option value='"+element.getIdemployee()+"'>"+
		    element.getFirstname()+" "+element.getLastname()+"</option>\n");
		}	
		
		return lstEmpl.toString();
	}
	
	public String getProjects(int employee)
	{
		List<com.javaee.ejb.entity.Project> projects = proj.GetProjets(employee);
		
		Iterator<com.javaee.ejb.entity.Project> iter = projects.iterator();
		StringBuilder lstProj = new StringBuilder();
		while (iter.hasNext()) {
		    com.javaee.ejb.entity.Project element = iter.next();

		    String pp = null;
		    
		    try {
		    	Employee e = emp.GetEmployeParId(element.getManagerIdemployee());
		    	pp = e.getFirstname()+" "+e.getLastname();
		    }
		    catch(Exception e)
		    {
		    	pp = "Unknown";
		    }
		    lstProj.append("<tr>" +
		    "<td><a href='Project?idProject="+element.getIdproject()+"'>"+element.getName()+"</a></td>" +
		    "<td>"+element.getDescription()+"</td>"+
		    "<td>"+element.getBudject()+"</td>"+
		    "<td>"+pp+"</td>"+
		    "<td><a href='Project?delete="+element.getIdproject()+"'>X</a></td>" +
		    "<td><a href='Project?activites="+element.getIdproject()+"'>Activites</a></td>" +
		    "</tr>\n");
		}	
		
		return lstProj.toString();
	}
	
	public String getProjectsManager(int employee)
	{
		List<com.javaee.ejb.entity.Project> projects = proj.GetProjetsManager(employee);
		
		Iterator<com.javaee.ejb.entity.Project> iter = projects.iterator();
		StringBuilder lstProj = new StringBuilder();
		while (iter.hasNext()) {
		    com.javaee.ejb.entity.Project element = iter.next();

		    String pp = null;
		    
		    try {
		    	Employee e = emp.GetEmployeParId(element.getManagerIdemployee());
		    	pp = e.getFirstname()+" "+e.getLastname();
		    }
		    catch(Exception e)
		    {
		    	pp = "Unknown";
		    }
		    lstProj.append("<tr>" +
		    "<td><a href='Project?idProject="+element.getIdproject()+"'>"+element.getName()+"</a></td>" +
		    "<td>"+element.getDescription()+"</td>"+
		    "<td>"+element.getBudject()+"</td>"+
		    "<td>"+pp+"</td>"+
		    "<td><a href='Project?delete="+element.getIdproject()+"'>X</a></td>"+
		    "<td><a href='Project?activites="+element.getIdproject()+"'>Activites</a></td>" +
		    "</tr>\n");
		}	
		
		return lstProj.toString();
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String budject = request.getParameter("budject");
		String description = request.getParameter("description");
		String manager = request.getParameter("manager");
		String idProject = request.getParameter("idProject");
		
		com.javaee.ejb.entity.Project p = new com.javaee.ejb.entity.Project();
		try{
			p.setBudject(Integer.parseInt(budject));
			p.setDescription(description);
			p.setName(name);
			p.setManagerIdemployee(Integer.parseInt(manager));
		}
		catch(NumberFormatException nfe)
		{
			error.add("le budget doit être un nombre");
		}
		if(name.equals(""))
			error.add("Le nom du projet est obligatoire");
		if(description.equals(""))
			error.add("La description du projet est obligatoire");
		
		if(error.isEmpty())
		{
			if(idProject != null)
			{
				p.setIdproject(Integer.parseInt(idProject));
				proj.UpdateProject(p);
			}
			else
				proj.AjouterProjet(p);
		}
		
		doGet(request, response);
	}

}
